<!-- frontend/src/components/ApiDemo.vue -->
<template>
  <div class="api-demo">
    <h2>API 演示</h2>

    <!-- 添加按钮触发API请求 -->
    <el-button type="primary" @click="fetchData">
      点击获取API数据
    </el-button>

    <!-- 显示加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 显示成功数据 -->
    <div v-if="data && !loading" class="result">
      <p><strong>消息:</strong> {{ data.message }}</p>
      <p><strong>时间戳:</strong> {{ data.timestamp }}</p>
    </div>

    <!-- 显示错误信息 -->
    <div v-if="error && !loading" class="error">
      <el-alert type="error" :title="error"></el-alert>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import axios from 'axios';

// 定义API响应类型
interface ApiResponse {
  message: string;
  timestamp: string;
}

const api = axios.create({
  baseURL: '/api',  // 生产环境路径
});
const fetchApiData = () => api.get<ApiResponse>('/data');

export default defineComponent({
  setup() {
    const data = ref<null | { message: string; timestamp: string }>(null);
    const error = ref('');
    const loading = ref(false);  // 添加加载状态

    const fetchDataFromApi = async () => {
      loading.value = true;  // 显示加载状态
      try {
        const response = await fetchApiData();
        data.value = response.data;
        error.value = '';
      } catch (err: any) {
        error.value = err.message || '请求失败';
      } finally {
        loading.value = false;  // 隐藏加载状态
      }
    };

    return {
      data,
      error,
      loading,
      fetchData: fetchDataFromApi  // 导出时使用原始名称
    };
  }
});
</script>

<style scoped>
.api-demo {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.loading {
  margin: 20px 0;
  color: #409EFF;
  font-weight: bold;
}

.result {
  margin: 20px 0;
  padding: 15px;
  background-color: #f0f9ff;
  border-left: 3px solid #409EFF;
  border-radius: 0 4px 4px 0;
}

.error {
  margin: 20px 0;
}
</style>